﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using Spider.Core;
using Spider.Entity;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;

namespace Spider
{
    public partial class Main : Form
    {
        Stopwatch sw = new Stopwatch();

        private SpiderEngin _spiderEngin;

        private ParserEngin _parserEngin;

        int i = 0;

        private IEnumerable<EmailInfo> _email;

        public Main()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            lbxMessage.Items.Clear();
            lbxUris.Items.Clear();
            textBox1.Text = "";

            _spiderEngin = new SpiderEngin();
            _spiderEngin.MainForm = this;
            _spiderEngin.DoSpider();

            label1.Text = "";
        }

        private void lbxUris_DoubleClick(object sender, EventArgs e)
        {
            ListBox box = sender as ListBox;
            textBox1.Text = box.SelectedItem.ToString();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(Save));
            thread.Start();
        }


        private void btnParse_Click(object sender, EventArgs e)
        {
            sw.Start();

            _parserEngin = new ParserEngin();
            _parserEngin.ParserCompleted += new ParserCompletedEventHandler(engin_ParserCompleted);
            _parserEngin.MainForm = this;
            _parserEngin.DoParse();

        }

        private void engin_ParserCompleted(object sender, ParserEventArgs e)
        {
            _email = e.Email.Distinct(new ComparEmail());
            MessageBox.Show(string.Format("email count  {0} ", _email.Count()));
            //   sw.Stop();
            //    MessageBox.Show(aaa.Count + "  ==  " + sw.ElapsedTicks.ToString());
        }


        public void Save()
        {
            string insert = string.Empty;

            try
            {
                foreach (var uri in _spiderEngin.uris)
                {
                    insert = string.Format("insert into uri values(null,'{0}',date('now'),0,'{1}','{2}')", uri.Key, uri.Value.Split(':')[1], uri.Value.Split(':')[0]);

                    //insert = "insert into name values('" + uri.Value.Replace("'", "|") + "')";

                    SQLHelper.ExecuteNonQuery(insert);

                    i++;

                    label1.Text = i + "";
                }

                MessageBox.Show("save success.");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            label2.Text = new ParserEngin().GetUris().Count.ToString();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            string update = " update uri set  state=1 ";

            SQLHelper.ExecuteNonQuery(update);

            MessageBox.Show("update success.");
        }

        private void btnSaveEmail_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(SaveEmail));
            thread.Start();
        }

        public void SaveEmail()
        {
            if (_email == null || _email.Count() == 0) return;

            string insert = string.Empty;
            i = 0;
            try
            {
                foreach (var email in _email)
                {
                    insert = "insert into email values(null,'" + email.Email + "',0,date('now'),'" + email.Type + "','" + email.City + "')";
                    SQLHelper.ExecuteNonQuery(insert);

                    i++;

                    label3.Text = i + "";
                }

                MessageBox.Show("save success.");
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void btnQQ_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<string, string> qq = new Dictionary<string, string>();

                string query = "select email,city from  email where email like  '%@qq.com'";

                DataTable dt = SQLHelper.ExecuteDataset(query).Tables[0];

                foreach (DataRow row in dt.Rows)
                {
                    string temp = row["email"].ToString().Replace("@qq.com", "");
                    if (!qq.Keys.Contains(temp))
                        qq.Add(temp, row["city"].ToString());
                }

                foreach (var item in qq)
                {
                    string insert = string.Format("insert into qq values('{0}','{1}','F','0')", item.Key, item.Value);
                    SQLHelper.ExecuteNonQuery(insert);
                }

                MessageBox.Show("Success");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        public class ComparEmail : IEqualityComparer<EmailInfo>
        {

            public bool Equals(EmailInfo x, EmailInfo y)
            {
                if (x == null && y == null)
                    return false;
                return x.Email == y.Email;
            }

            public int GetHashCode(EmailInfo obj)
            {
                return obj.ToString().GetHashCode();
            }
        }

        private void btnData_Click(object sender, EventArgs e)
        {
            DataEngin dataa = new DataEngin();
            List<Data> result = dataa.Run();

            if (dataa.Save(result) == 1)
                MessageBox.Show("save success");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = @"G:\source\Image\format";
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] files = dir.GetFiles();

            foreach (var item in files)
            {
                string temp = "images/face/f/" + item;
                string insert = string.Format("insert into face values('{0}')", temp);
                SQLHelper.ExecuteNonQuery(insert);
            }

            MessageBox.Show("Success");
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            WebClient client = new WebClient();
            byte[] buffer = client.DownloadData("http://www.yyq777.com/forum-15-25.html");
            string content = System.Text.Encoding.UTF8.GetString(buffer);

            IEnumerator enu = new Regex(@"(thread-\d{5}-1-1).*(\.html)")
                .Matches(content)
                .GetEnumerator();

            while (enu.MoveNext() && enu.Current != null)
                lbxUris.Items.Add(((Match)(enu.Current)).Value);
        }
    }
}






